package com.cti.commons.delayqueue.core;

import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.cti.commons.delayqueue.core.mode.DelayMessage;

/**
 * @author et.wang
 * @description: 延迟任务池
 * @date 2022/10/27 19:35
 */
public class DelayQueueJobPool {

    private static final Logger logger = LoggerFactory.getLogger(DelayQueueJobPool.class);

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 查询 延时任务池内容
     *
     * @param delayQueueJobId
     * @return
     */
    public DelayMessage getDelayQueueJob(long delayQueueJobId) {
        try {
            RMap<Long, DelayMessage> messageRMap = redissonClient.getMap(DelayQueueConstant.DELAY_QUEUE_JOB_POOL);
            return messageRMap.get(delayQueueJobId);
        } catch (Exception e) {
            logger.error("获取任务池元数据出错 id:{}", delayQueueJobId, e);
        }
        return null;
    }

    /**
     * 添加 延时任务池内容
     *
     * @param delayMessage
     */
    public void addDelayQueueJob(DelayMessage delayMessage) {
        RMap<Long, DelayMessage> messageRMap = redissonClient.getMap(DelayQueueConstant.DELAY_QUEUE_JOB_POOL);
        messageRMap.put(delayMessage.getId(), delayMessage);
    }

    /**
     * 删除 延时任务池内容
     *
     * @param delayQueueJobId
     */
    public void deleteDelayQueueJob(long delayQueueJobId) {
        RMap<Long, DelayMessage> messageRMap = redissonClient.getMap(DelayQueueConstant.DELAY_QUEUE_JOB_POOL);
        messageRMap.remove(delayQueueJobId);
    }

}
